package com.dhcc.DRGsHosp.facade.impl.quartzjob;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhcc.DRGsHosp.core.domain.ScheduleJob;
 
/**
 * @ClassName: QuartzJobFactory  
 * @Description ： 定时任务执行处 无状态   
 * @Date: 2018年10月10日 下午2:59:59  
 * @Author QiaoYiLong 
 * @Version 3.1.1 DHC-DRG
 */
public class QuartzJobFactory implements Job {
	private static final Logger logger = LoggerFactory.getLogger(QuartzJobFactory.class);
	
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
		invokMethod(scheduleJob);
	}

	/**
	 *  @Discription：通过反射调用scheduleJob中定义的方法
	 *  @Author： liuhongjun
	 *  @param scheduleJob
	 *  @Date:2018年10月24日下午10:33:14
	 */
	public static void invokMethod(ScheduleJob scheduleJob) {
		Object object = null;
		Class<?> clazz = null;
		if (StringUtils.isNotBlank(scheduleJob.getBeanClass())) {
			try {
				clazz = Class.forName(scheduleJob.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (object == null) {
			logger.error("定时任务方法未定义");
			return;
		}
		clazz = object.getClass();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(scheduleJob.getMethodName(), new Class[] { String.class });
			if (method != null) {
				String param = scheduleJob.getJobData();
				if(StringUtils.isEmpty(param)) {
					method.invoke(object,"dhcc");
				}else{
					method.invoke(object,param);
				}
			}
		} catch (NoSuchMethodException e) {
			logger.error(e.getMessage());
			e.printStackTrace();

		} catch (SecurityException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
	}
}